import React, { useContext, useState,useEffect} from 'react'
import classes from './cart.module.css'
import img from '../../assets/img/bag.png'
import Mycontext from '../Context/context'
import Cartdetail from './CartDetail/cartdetail'
import Checkout from '../Checkout'
export default function Cart() {
    const cxt=useContext(Mycontext)
    const [showdetail,setshowdetail]=useState(false)
    const [showcheckout,setshowcheckout]=useState(false)
    const showDetail=(e)=>{
        if(cxt.totalAmount!==0)
        e.stopPropagation();
        setshowdetail(true)
    }
    const noshowDetail=()=>{
      setshowdetail(false)
    }
    const Gochecked=()=>{
      if(cxt.totalAmount!==0)
      setshowcheckout(true)
      console.log(showcheckout)
    }
    const checkoutdisplay=()=>{
      setshowcheckout(false)
    }
    // eslint-disable-next-line
    useEffect(()=>{  
      if(cxt.totalAmount===0){
        setshowdetail(false);
        setshowcheckout(false)
      }
    },[cxt,setshowdetail,setshowcheckout])
  return (
    <div>
        <div onClick={noshowDetail}>
        {
            showdetail&&(cxt.totalAmount!==0)? <Cartdetail/>:null
        }
       </div>
       {
            showcheckout&&(cxt.totalAmount!==0)? <Checkout oncheckout={checkoutdisplay}/>:null
        }
    <div className={classes.cart} >
      <div className={classes.Icon} onClick={showDetail}>
        <img src={img} alt='' className={classes.img} ></img>
        {
        cxt.totalAmount===0?null:<span className={classes.num}>{cxt.totalAmount}</span>
        }
       
      </div>
      {
      cxt.totalAmount===0?<p className={classes.foodsnot}>未选择商品</p>:<p className={classes.price}>￥{cxt.totalPrice}</p>
      }
     
     <button
           onClick={Gochecked}
          className={`${classes.btn} ${cxt.totalAmount === 0 ? classes.Disabled : ''}`}>去结算</button>
        
    </div>
    </div>
  )
}
